package com.example.demo.controller;

import java.net.URI;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.dao.UserDao;
import com.example.demo.entity.User;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;

@RestController
public class ProviderUserController {
	
	@Autowired
	private EurekaClient eurekaClient;
	
	@Autowired
	private UserDao userdao;
	
	
	@Autowired
	private DiscoveryClient discoveryClient;
	
	@GetMapping("/getUser/{id}")
	public User getUserById(@PathVariable Long id) {
		return userdao.getOne(id);
	}
	
	
	@PostMapping("/getUser-test")
	public User getUser(@RequestBody User user) {
		return user;
	}
	
	@GetMapping("/microservice-user")
	public String serviceUrl() {
	    InstanceInfo instance = eurekaClient.getNextServerFromEureka("microservice-provider-user", false);
	    return instance.getHomePageUrl();
	}
	@GetMapping("/microservice-user2")
	public URI serviceUrl2() {
	    List<ServiceInstance> list = discoveryClient.getInstances("microservice-provider-user");
	    if (list != null && list.size() > 0 ) {
	        return list.get(0).getUri();
	    }
	    return null;
	}
}
